package com.yzt.message.custom;

import android.content.Context;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.yzt.message.R;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.zhuju.richtext.CacheEmojiManager;
import com.yzt.zhuju.richtext.entity.GiftBaseInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.rong.imkit.conversation.extension.component.emoticon.AndroidEmoji;
import io.rong.imkit.feature.destruct.DestructManager;
import io.rong.imkit.model.UiMessage;
import io.rong.imkit.widget.adapter.IViewProviderListener;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;

/**
 * 分享消息的容器
 */
public class RXShareMessageItemProvider extends CustomBaseMessageItemProvider<RXShareMessageContent> {

    public RXShareMessageItemProvider() {
        mConfig.showReadState = true;
        mConfig.showContentBubble = false;
    }

    @Override
    protected ViewHolder onCreateMessageContentViewHolder(ViewGroup parent, int i) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nomi_rc_item_share_message, parent, false);
        return new ViewHolder(view.getContext(), view);
    }

    @Override
    protected void bindMessageContentViewHolder(io.rong.imkit.widget.adapter.ViewHolder viewHolder, io.rong.imkit.widget.adapter.ViewHolder viewHolder1, RXShareMessageContent content, UiMessage data, int position, List<UiMessage> list, IViewProviderListener<UiMessage> iViewProviderListener) {
        ViewHolder holder = (ViewHolder) viewHolder;

        if (data.getMessageDirection() == Message.MessageDirection.SEND) {
            holder.llMainLeft.setVisibility(View.GONE);
            holder.llMain.setVisibility(View.VISIBLE);
            holder.llMain.setBackgroundResource(R.drawable.rc_circle_bubble_right);
            holder.message.setTextColor(ContextCompat.getColor(holder.message.getContext(), R.color.color_262628));
        } else {
            holder.llMainLeft.setVisibility(View.VISIBLE);
            holder.llMain.setVisibility(View.GONE);
            holder.llMainLeft.setBackgroundResource(R.drawable.rc_circle_bubble_left);
            holder.message.setTextColor(ContextCompat.getColor(holder.message.getContext(), R.color.color_262628));
        }

        holder.message.setVisibility(View.VISIBLE);
        holder.messageLeft.setVisibility(View.VISIBLE);
        Map<String, Object> extra = content.getMyExtra();

        holder.message.setText(content.getContent().replace("[", "").replace("]", ""));
        holder.messageLeft.setText(content.getContent().replace("[", "").replace("]", ""));

        holder.tvHiTextRight.setVisibility(View.VISIBLE);

        if (extra != null && extra.size() > 0) {

            if (extra.containsKey("giftIcon")) {
                String giftIcon = (String) extra.get("giftIcon");
                if (extra.get("isGreetGift") != null) {
                    boolean isGreetGift = (boolean) extra.get("isGreetGift");

                    if (isGreetGift) {
                        CharSequence charSequence;
                        String htmlContent = "送你<font color='#FF6550'>1</font>个打招呼礼物";
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            charSequence = Html.fromHtml(htmlContent, Html.FROM_HTML_MODE_LEGACY);
                        } else {
                            charSequence = Html.fromHtml(htmlContent);
                        }

                        if (data.getMessageDirection() == Message.MessageDirection.SEND) {
                            holder.tvHiTextRight.setVisibility(View.GONE);
                            holder.message.setText(charSequence);
                        } else {
                            holder.tvHiTextLeft.setVisibility(View.GONE);
                            holder.messageLeft.setText(charSequence);
                        }

                        RongIMClient.getInstance().setMessageExtra(data.getMessageId(), "1", new RongIMClient.ResultCallback<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {

                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {

                            }
                        });
                    }
                }

                ImageLoadUtil.loadIv(holder.ivPhoto.getContext(), giftIcon, holder.ivPhoto);
                ImageLoadUtil.loadIv(holder.ivPhotoLeft.getContext(), giftIcon, holder.ivPhotoLeft);
            } else {
                ImageLoadUtil.loadIv(holder.ivPhoto.getContext(), getGiftUrl(content.getContent()), holder.ivPhoto);
                ImageLoadUtil.loadIv(holder.ivPhotoLeft.getContext(), getGiftUrl(content.getContent()), holder.ivPhotoLeft);
            }
        } else {
            ImageLoadUtil.loadIv(holder.ivPhoto.getContext(), getGiftUrl(content.getContent()), holder.ivPhoto);
            ImageLoadUtil.loadIv(holder.ivPhotoLeft.getContext(), getGiftUrl(content.getContent()), holder.ivPhotoLeft);
        }
    }

    @Override
    protected boolean onItemClick(io.rong.imkit.widget.adapter.ViewHolder viewHolder, RXShareMessageContent content, UiMessage message, int position, List<UiMessage> list, IViewProviderListener<UiMessage> iViewProviderListener) {
        ViewHolder holder = (ViewHolder) viewHolder;
        if (content != null && content.isDestruct() && !(message.getMessage().getReadTime() > 0)) {
            holder.message.setVisibility(View.VISIBLE);
            processTextView(holder.itemView, content, holder.message, holder.ivPhoto);
            DestructManager.getInstance().startDestruct(message.getMessage());
        }
        return false;
    }

    @Override
    protected boolean isMessageViewType(MessageContent messageContent) {
        return messageContent instanceof RXShareMessageContent && !messageContent.isDestruct();
    }

    @Override
    public Spannable getSummarySpannable(Context context, RXShareMessageContent data) {
        if (data == null) {
            return null;
        }
        String content = data.getContent();
        if (content != null) {
            if (content.length() > 100) {
                content = content.substring(0, 100);
            }
            return new SpannableString(AndroidEmoji.ensure(content));
        }
        return null;
    }

    private static class ViewHolder extends io.rong.imkit.widget.adapter.ViewHolder {
        TextView message, messageLeft;
        LinearLayout llMain, llMainLeft;
        ImageView ivPhoto, ivPhotoLeft;
        TextView tvHiTextRight, tvHiTextLeft;

        public ViewHolder(Context context, View view) {
            super(context, view);

            this.llMain = view.findViewById(R.id.ll_main);
            this.llMainLeft = view.findViewById(R.id.ll_main_left);
            this.message = view.findViewById(R.id.tv_content);
            this.messageLeft = view.findViewById(R.id.tv_content_left);
            this.ivPhoto = view.findViewById(R.id.iv_photo);
            this.ivPhotoLeft = view.findViewById(R.id.iv_photo_left);
            this.tvHiTextRight = view.findViewById(R.id.tv_hi_text_right);
            this.tvHiTextLeft = view.findViewById(R.id.tv_hi_text_left);
        }
    }

    private String getGiftUrl(String content) {
        //礼物 表情
        Pattern p = Pattern.compile("\\[\\w+\\]");
        Matcher m = p.matcher(content);
        String path = null;
        while (m.find()) {
            String faceKey = m.group();
            if (faceKey != null) {
                path = getGiftDrawable(faceKey);
                break;
            }
        }
        return path;
    }

    private static List<GiftBaseInfo> mGifts = new ArrayList<>();

    private String getGiftDrawable(String faceKey) {

        if (mGifts == null || mGifts.isEmpty()) {
            mGifts = CacheEmojiManager.getInstance().getGiftList();
        }
        if (mGifts == null || mGifts.isEmpty()) {
            return null;
        }
        for (GiftBaseInfo giftData : mGifts) {
            if (faceKey.contains(giftData.giftName)) {
                return giftData.icon;
            }
        }
        return null;
    }

    private void processTextView(final View v, final RXShareMessageContent content, final TextView pTextView, final ImageView ivGift) {
        if (content.getContent() != null) {
            int len = content.getContent().length();
            //文本消息过大，缓解下拉滑动时的卡顿问题
            if (v.getHandler() != null && len > 500) {
                v.getHandler().postDelayed(() ->
                        pTextView.setText(content.getContent()), 50
                );
            } else {
                pTextView.setText(content.getContent());
            }
            ImageLoadUtil.loadIv(ivGift.getContext(), getGiftUrl(content.getContent()), ivGift);
        }
    }
}